//
//  NCBTImage.m
//  BaiduTravel
//
//  Created by neu on 11-9-10.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "NCBTImage.h"
#import <QuartzCore/QuartzCore.h>

#import "UIImageView+WebCache.h"
#import "UIImageView+CutToResize.h"
#import "NSString+NSString_Ex_.h"

@implementation NCBTImage

@synthesize dropTouchEvent = _dropTouchEvent;
@synthesize url = _url;
@synthesize bgImageName = _bgImageName;
@synthesize border = _border;
@synthesize image = _image;
@synthesize isDownloaded = _isDownloaded;
@synthesize isShowOriginDownloadPic = _isShowOriginDownloadPic;

#ifdef NCBTImageHasWaiting
@synthesize waitingImageName = _waitingImageName;
@synthesize centerWaiting = _centerWaiting;
#endif

#define kScreenWidth                        320
#define kScreenHeight                       UIScreenHeight

#pragma mark -
#pragma mark Private Method

#ifdef NCBTImageHasWaiting
- (void)showLoadingWheel 
{
	// Make sure previous loading view is released.
	[_loadingWheel removeFromSuperview];
	
	// Create new loading view.
	UIActivityIndicatorView *loadingView = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
	CGSize size = self.frame.size;
    if (_centerWaiting)
    {
        CGPoint pt = CGPointMake(kScreenWidth/2.0,kScreenHeight/2.0);
        CGRect rct=CGRectZero;
        rct.origin.x = pt.x - loadingView.frame.size.width/2.0;
        rct.origin.y = pt.y - loadingView.frame.size.height/2.0;
        rct.size = loadingView.frame.size;
        loadingView.frame = rct;
    }
    else
    {
        loadingView.center = CGPointMake(size.width/2.0, size.height/2.0);
    }
	loadingView.hidesWhenStopped = YES;
	[loadingView startAnimating];
    if(size.width == 0 || size.height==0)
    {
        loadingView.hidden = YES;
    }
	[self addSubview:loadingView];
	
	_loadingWheel = loadingView;
}
#endif

#ifdef NCBTImageHasWaiting
- (void)hideLoadingWheel 
{
	[_loadingWheel stopAnimating];
	[_loadingWheel removeFromSuperview];
	_loadingWheel = nil;
}
#endif

#ifdef NCBTImageHasWaiting
- (void)showWaiting
{
    if(_waitingImageName)
    {    
        [_waitingImageView removeFromSuperview];
        _waitingImageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:_waitingImageName]] autorelease];
        CGSize sz=_waitingImageView.image.size;
        if (_centerWaiting)
        {
            CGPoint pt = CGPointMake(kScreenWidth/2.0,kScreenHeight/2.0);
            CGRect rct=CGRectZero;
            rct.origin.x = pt.x - sz.width/2.0;
            rct.origin.y = pt.y - sz.height/2.0;
            rct.size = sz;
            _waitingImageView.frame = rct  ;
            _waitingImageView.center = pt;
        }
        else
        {
            _waitingImageView.frame = self.frame;
        }
        [self addSubview:_waitingImageView];
    }
    else
    {
        [self showLoadingWheel];
    }
}
#endif

#ifdef NCBTImageHasWaiting
- (void)hideWaiting
{
    if(_waitingImageView)
    {
        [_waitingImageView removeFromSuperview];
        _waitingImageView = nil;
    }else
    {
        [self hideLoadingWheel];
    }
}
#endif

#pragma mark -
#pragma mark Request Delegate Method

-(void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image{
    NSData *data;
    data = UIImageJPEGRepresentation(image, 1.0);
    if (data == nil) {
        data = UIImagePNGRepresentation(image);
    }
    float dataSize = (float)data.length/1024.0f; //Modified by chenjiedan ：增加判断，如果size小于1KB 可能图片异常，不进行存储。
    if ( dataSize < 1)      return;
    [self setDownLoadOrginPic:image];
    _isDownloaded = YES;
    
    [self downloadFinished];
}

- (void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error{
#ifdef NCBTImageHasWaiting
	[self hideLoadingWheel];
#endif
}


- (void)setUrl:(NSString*)aUrl
{
    if (!aUrl || ![aUrl isKindOfClass:[NSString class]])
    {
        return;
    }
    
    [aUrl retain];
    [_url release];
    _url = aUrl;
    
    
    if ([NSString stringIsNullOrEmpty:aUrl])
    {
        //NSLog(@"invalid url:nil or \"\"");
        return;
    }
    
    NSString *urlString = [[NSString stringWithFormat:@"%@",aUrl] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSString *scheme = [url scheme];
    if (![scheme isEqualToString:@"http"]){
        UIImage *image = [UIImage imageWithContentsOfFile:aUrl];
        [self setDownLoadOrginPic:image];
        [self downloadFinished];
        return;
    }
    NSData *imageData = nil;
    if(imageData)
    {
        //[self downloadFinished];
//        imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:aUrl]];
        UIImage *image = [UIImage imageWithData:imageData];
        [self setDownLoadOrginPic:image];
        [self setNeedsDisplay];
        [self downloadFinished];
        //NSLog(@"NCBTImage :find cache:%@",aUrl);
        return;
    }
#ifdef NCBTImageHasWaiting
    [self showWaiting];
#endif
    
    [self setImageWithURL:[NSURL URLWithString:aUrl]];
//    NSString *codeUrl= [aUrl stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    RequestGeneral *request = [[[RequestGeneral alloc]
//											   initWithRequestParam:aUrl] autorelease];
//	
//	
//	_request = [[BTHTTPRequest alloc] initWithRequest:request];
//	[_request setDelegate:self];
//
//	
//	// Fetch new xml in fresh.
//	[AppEngine appendImageHttpRequest:_request
//						delegate:self 
//			   didFinishSelector:@selector(requestFinished:)
//				 didFailSelector:@selector(requestFailed:)];
}

#ifdef NCBTImageHasWaiting
- (void)setWaitingImageName:(NSString*)aWaitingImageName
{
    [aWaitingImageName retain];
    [_waitingImageName release];
    _waitingImageName = aWaitingImageName;
    [self showWaiting];
}
#endif

#pragma mark -
#pragma mark Override base functions
- (id)initWithFrame:(CGRect)frame URL:(NSString*)URL
{
    if ((self = [super initWithFrame:frame])) {
        self.userInteractionEnabled = NO; // Turn this back on if you want to catch taps.

#ifdef NCBTImageHasWaiting
        [self showLoadingWheel];
#endif

        [self setUrl:URL];
    }
    return self;
}

- (void) setDownLoadOrginPic:(UIImage *)aImage
{
    [aImage retain];
    [_image release];
    _image = aImage;
    CGSize imgSize = aImage.size;
    CGRect rect = CGRectZero;
    rect.origin.x = 0;
    rect.origin.y = 0;
    rect.size = imgSize;
    super.frame = rect;

#ifdef NCBTImageHasWaiting
    if (_loadingWheel)
    {
        [_loadingWheel removeFromSuperview];
        _loadingWheel = nil;
    }
    if (_waitingImageView)
    {
        [_waitingImageView removeFromSuperview];
        _waitingImageView = nil;
    }
#endif
    if (_realImageView)
    {
        [_realImageView removeFromSuperview];
        _realImageView = nil;
    }
    UIImageView *imageView=[[[UIImageView alloc] initWithFrame:rect] autorelease];
    imageView.image = _image;
    _realImageView = imageView;
    [self addSubview:_realImageView];
}

- (void)dealloc {
    _delegate = nil;
    _selector = nil;
    _downloadDelegate = nil;
    _downloadSelector = nil;
    
    [_bgImageName release];
#ifdef NCBTImageHasWaiting
    [_waitingImageName release];
#endif
    [_image release];
    [_url release];
    [super dealloc];
}

#pragma mark -
#pragma mark Download finished call back
- (void)downloadFinished
{
    
	if (_downloadDelegate != nil && [_downloadDelegate respondsToSelector:_downloadSelector]){
		[_downloadDelegate performSelector:_downloadSelector withObject:self];
	}
}


#pragma mark -
#pragma mark Public functions
- (void)setCallbackOnDownloadFinished:(id)delegate withSelector:(SEL)selector {
	_downloadDelegate = delegate;
	_downloadSelector = selector;
	self.userInteractionEnabled = YES; // User interaction is not enabled in the initializer.
}

#pragma mark -
#pragma mark Override UIResponder functions
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
    if (_dropTouchEvent == NO)
    {
        // no to send the event to the parent.
        [super touchesEnded:touches withEvent:event];
    }
	if (_delegate && [_delegate respondsToSelector:_selector]){
		[_delegate performSelector:_selector withObject:self];
	}
}

#pragma mark -
#pragma mark Public functions
- (void)setCallbackOnImageTap:(id)delegate withSelector:(SEL)selector {
	_delegate = delegate;
	_selector = selector;
	self.userInteractionEnabled = YES; // User interaction is not enabled in the initializer.
}

@end
